package com.h3bpm.handler;

import OThinker.H3.Entity.IEngine;
import com.alibaba.fastjson.JSONObject;
import com.h3bpm.web.common.utils.HttpLocalUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/** 获取用户的iD 存储token
 * Created by wjq on 2019/12/12.
 */
public class UserHelper {

    private static final Logger logger = LoggerFactory.getLogger(UserHelper.class);
    /**
     * 任务中心 系统 Restful 接口地址  {#接口地址}/oauth/token
     */

    private static String Content_Type="application/json; charset=utf-8";
    private static String method="POST";
    private static Integer ONE=1;
    private static Integer TWO=2;
    private static Integer There=3;
    private static Integer FOUR=4;
    private static Integer FIVE=5;
    private static Integer SIX=6;
    private static Integer ZERO=0;
    private static Integer TIMES=1000;
     //测试
    //public static String PORTAL_URL = "http://bpm.test.zhejianglab.com";
    //正式
     //public static String PORTAL_BUSINESS= "http://120.25.219.66/";

    //正式 bpm地址
    //public static String PORTAL_BPM = "http://120.25.219.66:8082/";

    /**
     * 获取用户的id
     */
    public static String judgeToken(String businessUrl){
        String accessToken =null;
        accessToken = (String) LocalCacheClient.get("access_token");
        if(accessToken==null||accessToken.isEmpty()||"".equals(accessToken)){
            accessToken = getToken(businessUrl);
        }
        Long time = (Long) LocalCacheClient.get("time");
        if(time==null||"".equals(time)||(System.currentTimeMillis()-time)>60000){
            accessToken = getToken(businessUrl);
        }
        logger.debug("返回token————————access_token——————"+accessToken);
        return accessToken;
    }
    /*
    * 获取token并存在缓存中
    * */
    public  static  String  getToken(String businessUrl){
        try {
        //封装json
            String accessToken="";
        JSONObject map = new JSONObject();
        String url = businessUrl+"" +
                "/prod-api/getToken";
            Map<String, Object> objectObjectMap = new HashMap<>();
            String requestString =null;
             requestString =  HttpLocalUtils.doPost(url,objectObjectMap,"application/x-www-form-urlencoded",null);
             if(requestString==null||"".equals(requestString)){
                 }else {
                   Map<String, Object> stringObjectMap = JSONUtils.parseMap(requestString);
                 accessToken = (String) stringObjectMap.get("token");
                 accessToken="Bearer "+accessToken;
                 Long timeMillis = System.currentTimeMillis();
                 LocalCacheClient.set("token", accessToken);
                 LocalCacheClient.set("time", timeMillis);
               return accessToken;
             }
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }


    /**
     *
     * 发送数据  没有返回值
     *
     * 当发送失败时根据配置次数重试
     * @param times 休眠时间 毫秒
     * @param failAgain 失败后尝试次数
     * @param paramMap 请求内容
     * @return 返回 null/"" 时成功,否则返回失败内容
     */
    private static Boolean postRequestNoResult(String postUrl,String paramMap, String contentType,String authorization, int failAgain,int times,IEngine engine,String instanceCode,String taskId){
        int i = 0;
        String result = null;
        while (true){

            String requestString=null;
            System.out.println("发送前——————————————————-"+postUrl+"___"+paramMap+"====="+authorization);
            requestString = HttpLocalUtils.doPost2(postUrl,paramMap,authorization);
            System.out.println("发送后———————requestString——————"+requestString);
            // 发送后返回信息
            try {

                if(StringUtils.isNotBlank(requestString)){
                    Map<String, Object> stringObjectMap = JSONUtils.parseMap(requestString);
                    System.out.println("发送后———————stringObjectMap.get(\"Message\")——————"+stringObjectMap.get("Message"));
                    if( "".equals(stringObjectMap.get("Message"))||stringObjectMap.get("Message")==null){
                        Thread.sleep(5000);  //1000毫秒就是1秒
                    } else {
                       if("Success".equals(stringObjectMap.get("Message"))){
                           Map<String, Object> map = (Map<String, Object>) stringObjectMap.get("Result");
                           logger.info("--------------------"+(String) map.get("message"));
                           Boolean res =  (Boolean) map.get("success");
                           if(res){
                               return res;
                           }else{
                               logger.info("不成功存储异常————————————"+(String) map.get("message"));
                               return res;
                           }

                       }
                    }
                }

            } catch (Exception e){
                System.out.println(e.getMessage());
            }
            i ++;
            if(i > failAgain) {
                break; // 大于尝试次数退出
            }
        }
        return false;
    }
    /**
     *
     * 发送数据
     *
     * 当发送失败时根据配置次数重试
     * @param times 休眠时间 毫秒
     * @param failAgain 失败后尝试次数
     * @param paramMap 请求内容
     * @return 返回 null/"" 时成功,否则返回失败内容
     */
    public static Map<String, Object> postRequestResult(String postUrl,String paramMap,
          String contentType,String authorization, int failAgain,int times,
            IEngine engine,String instanceCode,String flag,String taskID){
        String url = null;
        int i = 0;
        while (true){
            String requestString=null;
            String json = JSONUtils.toJson(paramMap);
            System.out.println("发送前——————————————————-"+postUrl+"___"+json+"====="+authorization);
            requestString = HttpLocalUtils.doPost2(postUrl,paramMap,authorization);
            System.out.println("发送后——————————————————-"+requestString);
            // 发送后返回信息
            try {
                if(StringUtils.isNotBlank(requestString)){
                    Map<String, Object> stringObjectMap = JSONUtils.parseMap(requestString);
                    if( "".equals(stringObjectMap.get("Message"))||stringObjectMap.get("Message")==null){
                        Thread.sleep(5000);  //1000毫秒就是1秒
                    } else {
                        if("Success".equals(stringObjectMap.get("Message"))){
                            return (Map<String, Object>) stringObjectMap.get("Result");
                        }
                    }
                }
            } catch (Exception e){
                System.out.println(e.getMessage());
            }
            i ++;
            if(i > failAgain) {
                //不成功的时候保存进入数据库
                break;
            }
            // 大于尝试次数退出
        }
        return null;
    }
    /**
     *
     * 发送数据  protal 使用
     *
     * 当发送失败时根据配置次数重试
     * @param times 休眠时间 毫秒
     * @param failAgain 失败后尝试次数
     * @param paramMap 请求内容
     * @return 返回 null/"" 时成功,否则返回失败内容
     */
    public static Map<String, Object> postRequestResult2(String postUrl,String paramMap,String authorization, int failAgain,int times){
        String url = null;
        int i = 0;
        while (true){
            String requestString=null;
            String json = JSONUtils.toJson(paramMap);
            System.out.println("发送前——————————————————-"+postUrl+"___"+json+"====="+authorization);
            requestString = HttpLocalUtils.doPost2(postUrl,paramMap,authorization);
            System.out.println("发送后——————————————————-"+requestString);
            // 发送后返回信息
            try {
                if(StringUtils.isNotBlank(requestString)){
                    Map<String, Object> stringObjectMap = JSONUtils.parseMap(requestString);
                    if( "".equals(stringObjectMap.get("Message"))||stringObjectMap.get("Message")==null){
                        Thread.sleep(5000);  //1000毫秒就是1秒
                    } else {
                        if("Success".equals(stringObjectMap.get("Message"))){
                            return (Map<String, Object>) stringObjectMap.get("Result");
                        }
                        if("Exception".equals(stringObjectMap.get("Message"))){
                            return (Map<String, Object>) stringObjectMap.get("ResponseException");


                        }
                    }
                }
            } catch (Exception e){
                System.out.println(e.getMessage());
            }
            i ++;
            if(i > failAgain) {
                //不成功的时候保存进入数据库
                break;
            }
            // 大于尝试次数退出
        }
        return null;
    }

    /*

      wjq
      pc端url

     */
    public  static  String  pcUrl(String schemaCode,String flowid){
        String pcurl =  String.format("/Portal/run.html?SheetCode=S%s&Mode=Work&WorkItemID=%s&T=%ts&localLan=zh_CN&flag=2",
                schemaCode, flowid, new Date()); // PC地址

      // String pcurl = UrlConfig.BPMURL+ String.format("/Portal/InstanceSheets.html?InstanceId=%s", instanceId); // PC地址

       return  pcurl;
   }
    /*

     wjq
     pc端url

    */
    public  static  String  pcInsUrl(String instanceId){
        String pcurl =  String.format("/Portal/run.html?InstanceId=%s&flag=3", instanceId); // PC地址
        return  pcurl;
    }

    /*

     wjq
     app端url

    */
    public  static  String  h5InsUrl(String instanceId){
        String pcurl =  String.format("/Portal/MobileRun.html?InstanceId=%s&flag=3", instanceId); // PC地址
        return  pcurl;
    }

    /*

      wjq
      h5端url

     */
    public  static  String  h5Url(String schemaCode,String flowid){
         String h5Url=String.format("/Portal/MobileRun.html?loginfrom=dingtalk&SheetCode=S%s&WorkItemID=%s&T=%ts&flag=2",
                schemaCode, flowid, new Date());// APP地址
        return  h5Url;
    }

    /*
    拼接标题
    */
    public static String splitTitle(String originatorName,String instanceName){
        return String.format("%s发起的%s等待您的处理",originatorName, instanceName);
    }

    /*

    wjq
    pc端url

   */
    public  static  String  pcAllUrl(String schemaCode,String flowid, String instanceId){
        String pcurl =  String.format("/Portal/run.html?SheetCode=S%s&Mode=Work&WorkItemID=%s&T=%ts&localLan=zh_CN&flag=2&InstanceId=%s",
                schemaCode, flowid, new Date(), instanceId); // PC地址
        return  pcurl;
    }
}
